<template>
  <div id="app" :class="{ 'is-home': $route.path === '/' }">
    <ThreeJsSplash ref="splashScreen" />
    <TheHeader @logo-click="showSplashScreen" />
    <!-- <TheHeader /> -->
    <MobileMenu />
    <SearchDialog />
    <router-view class="main-container" />
    <TheFooter />
    <FloatingButtons />
    <Lantern />
    <div class="cursor-container"></div>
    <ContextMenu ref="contextMenuRef" />

    <!-- 全局链接跳转提示框 -->
    <mj-link-jump-prompt ref="globalLinkJumpPrompt" />

    <!-- 全局加载动画 -->
    <Loading ref="globalLoading" v-if="isLoadingInitialized" :visible="isLoadingComputed" />
    <MusicPlayer />
    <MusicDetail />
  </div>

</template>

<script>
import TheHeader from '@/layout/Header/index.vue'
import TheFooter from '@/layout/Footer/index.vue'
import FloatingButtons from '@/components/common/FloatingButtons.vue'
import { getWebConfigApi, reportApi, getNoticeApi } from '@/api/site'
import { mapActions, mapState } from 'vuex'
import { initTheme } from '@/utils/theme'
import Vue from 'vue'
import SearchDialog from '@/components/Search/index.vue'
import MobileMenu from '@/layout/MobileMenu/index.vue'
import Lantern from '@/components/Lanterns/index.vue'
import { getCookie, removeCookie } from '@/utils/cookie'
import ContextMenu from '@/components/ContextMenu/index.vue'
import ThreeJsSplash from '@/components/SplashScreen/ThreeJsSplash.vue'
import Loading from '@/components/common/Loading.vue'
import MusicPlayer from '@/components/MusicPlayer/index.vue'
import MusicDetail from '@/views/music/index.vue'

export default {
  name: 'App',
  components: {
    TheHeader,
    TheFooter,
    FloatingButtons,
    SearchDialog,
    MobileMenu,
    Lantern,
    ContextMenu,
    ThreeJsSplash,
    Loading,
    MusicPlayer,
    MusicDetail
  },
  data() {
    return {
      // 其他数据...
      savedScrollPosition: 0,
      isLoadingInitialized: false,
      isLoadingComputed: false
    }
  },
  computed: {
    ...mapState('music', ['showMusicDetail']),
    // 确保store存在时再使用mapState
    ...mapState({
      storeIsLoading: state => state && state.isLoading
    })
  },
  watch: {
    showMusicDetail(isShown) {
      if (isShown) {
        document.body.classList.add('no-scroll');
      } else {
        document.body.classList.remove('no-scroll');
      }
    },
    // 观察store中的isLoading状态变化
    storeIsLoading: {
      handler(newValue) {
        // 只有当值确实存在时才更新本地状态
        if (typeof newValue !== 'undefined') {
          this.isLoadingComputed = newValue;

          // 如果Loading组件已经挂载，控制其显示状态
          if (this.$refs.globalLoading) {
            if (newValue) {
              this.$refs.globalLoading.show && this.$refs.globalLoading.show();
            } else {
              this.$refs.globalLoading.hide && this.$refs.globalLoading.hide();
            }
          }
        }
      },
      immediate: true
    },
    '$route'() {
      // 路由变化后，稍等片刻检查内容是否已加载
      setTimeout(() => {
        // 检查是否已经在通知内容准备好，避免重复调用
        if (window._isNotifyingContentReady) {
          console.log('Already notifying content ready, skipping route change check');
          return;
        }

        if (this.$store && this.$store.state && this.$store.state.isLoading) {
          console.log('App.vue: 路由变化后检测内容加载状态');
          // 通知内容已准备好
          if (this.$contentReady) {
            this.$contentReady();
          }
        }
      }, 1500); // 给予足够的时间让内容加载
    }
  },
  async created() {
    // 首先初始化基本数据，然后再初始化依赖Vuex的功能
    try {
      await reportApi()
      const res = await getWebConfigApi()
      this.setSiteInfo(res.data)

      // 确保store已初始化
      if (this.$store) {
        this.$store.commit('setVisitorAccess', res.extra.visitorCount)
        this.$store.commit('setSiteAccess', res.extra.blogViewsCount)

        const noticeRes = await getNoticeApi()
        this.$store.commit('SET_NOTICE', noticeRes.data)
      }

      initTheme()
      await this.handleThirdPartyLogin()

      // 等待第三方登录处理完成再获取用户信息
      await this.getUserInfo();

      // 跳转到缓存地址
      let url = getCookie('redirectUrl')
      if (url) {
        removeCookie('redirectUrl')
        window.location.href = url
      }

      // 加载站点信息
      this.$store.dispatch("setSiteInfo");
      this.$store.dispatch("music/loadInitialData");
    } catch (error) {
      console.error('App初始化过程中出错:', error);
    }

    // 在created末尾启用loading状态
    this.$nextTick(() => {
      this.isLoadingInitialized = true;
    });
  },
  mounted() {
    this.initCursorEffect()
    this.initContextMenu()

    // 监听开屏动画显示
    this.$root.$on('splash-shown', this.saveScrollPosition);

    // 监听开屏动画结束
    this.$root.$off('splash-hidden'); // 避免重复绑定
    this.$root.$on('splash-hidden', this.restoreScrollPosition);

    // 确保全局链接跳转提示框引用可用
    this.$nextTick(() => {
      if (this.$refs.globalLinkJumpPrompt) {
        Vue.prototype.$linkJumpPrompt = this.$refs.globalLinkJumpPrompt;
        console.log('链接跳转提示框已全局注册 (mounted)');
      } else {
        console.warn('链接跳转提示框组件未找到');
      }

      // 将Loading组件引用暴露给全局Vue实例
      if (this.$refs.globalLoading) {
        Vue.prototype.$loading = this.$refs.globalLoading;
        console.log('全局Loading组件已注册');
      }
    });

    // 确保加载状态能够正确结束
    setTimeout(() => {
      // 防止递归调用
      if (window._isNotifyingContentReady) {
        console.log('Already notifying content ready, skipping initial loading check');
        return;
      }

      if (this.$store && this.$store.state && this.$store.state.isLoading) {
        console.log('App.vue: 初始加载后强制结束加载状态');
        if (this.$contentReady) {
          this.$contentReady();
        } else if (this.$store && this.$store.dispatch) {
          this.$store.dispatch('contentReady');
        }
      }
    }, 3000);

    window.addEventListener("scroll", this.handleScroll);
  },
  methods: {
    ...mapActions(['setSiteInfo', 'getUserInfo']),

    // 保存滚动位置
    saveScrollPosition() {
      this.savedScrollPosition = window.scrollY;
    },

    // 恢复滚动位置
    restoreScrollPosition() {
      setTimeout(() => {
        window.scrollTo(0, this.savedScrollPosition);
      }, 100);
    },

    showSplashScreen() {
      if (this.$refs.splashScreen) {
        this.$refs.splashScreen.showSplashScreen();
      }
    },

    /**
     * 处理第三方登录用回调逻辑
     */
    async handleThirdPartyLogin() {
      let flag = window.location.href.indexOf("token") != -1;
      if (flag && this.$store) {
        let token = window.location.href.split("token=")[1];
        this.$store.commit('SET_TOKEN', token);
      }
    },

    /**
     * 初始化鼠标点击效果
     */
    initCursorEffect() {
      const container = document.querySelector('.cursor-container')
      if (!container) return;

      document.addEventListener('click', (e) => {
        const cursor = document.createElement('div')
        cursor.className = 'cursor-fx'
        cursor.style.left = `${e.clientX}px`
        cursor.style.top = `${e.clientY}px`
        container.appendChild(cursor)

        cursor.addEventListener('animationend', () => {
          cursor.remove()
        })
      })
    },

    initContextMenu() {
      if (!this.$refs.contextMenuRef) return;

      const handleContextMenu = (e) => {
        // 在IM路由下不显示ContextMenu，使用RightMenu代替
        if (this.$route.path.startsWith('/im')) {
          return;
        }

        if (this.$refs.contextMenuRef && this.$refs.contextMenuRef.show) {
          this.$refs.contextMenuRef.show(e)
        }
      }

      const handleClick = () => {
        // 在IM路由下不处理ContextMenu的隐藏
        if (this.$route.path.startsWith('/im')) {
          return;
        }

        if (this.$refs.contextMenuRef && this.$refs.contextMenuRef.hide) {
          this.$refs.contextMenuRef.hide()
        }
      }

      document.addEventListener('contextmenu', handleContextMenu)
      document.addEventListener('click', handleClick)

      // 在组件销毁时移除事件监听
      this.$once('hook:beforeDestroy', () => {
        document.removeEventListener('contextmenu', handleContextMenu)
        document.removeEventListener('click', handleClick)
      })
    },

    handleScroll() {
      // Implementation of handleScroll method
    }
  },
  beforeDestroy() {
    // 移除事件监听
    this.$root.$off('splash-shown', this.saveScrollPosition);
    this.$root.$off('splash-hidden', this.restoreScrollPosition);
  }
}
</script>

<style lang="scss">
@import 'animate.css';
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

* {
  margin: 0;
  padding: 0;
  font-family: "font";
  box-sizing: border-box;
}

/* 鼠标点击效果 */
.cursor-fx {
  position: fixed;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: rgba(64, 158, 255, 0.6);
  pointer-events: none;
  z-index: 9999;
  animation: cursor-fx 0.8s forwards;
  transform: translate(-50%, -50%);
}

@keyframes cursor-fx {
  0% {
    opacity: 1;
    width: 0px;
    height: 0px;
  }

  100% {
    opacity: 0;
    width: 80px;
    height: 80px;
  }
}

/* 外部链接样式 */
a.external-link {
  position: relative;

  &::after {
    content: "↗";
    font-size: 0.85em;
    display: inline-block;
    margin-left: 2px;
    transition: transform 0.2s ease;
  }

  &:hover::after {
    transform: translate(2px, -2px);
  }
}

.no-scroll {
  overflow: hidden !important;
}

#app {
  display: flex;
  flex-direction: column;
}
</style>